﻿using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Project13776616780_01.Model;
using Project13776616780_01.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Project13776616780_01.Pages
{
    public partial class Gen
    {
        [Inject]
        private GlobalConfig config { get; set; }
        [Inject]
        DocsDbContext dbContext { get; set; }
        private bool generating;
        private List<GenModel> gens = new List<GenModel>();

        private async Task GenAllAsync()
        {
            var template = dbContext.Set<AppSetting>().FirstOrDefault(x => x.Name == Enums.AppSettingName.Template);
            var nameprefix = dbContext.Set<AppSetting>().FirstOrDefault(x => x.Name == Enums.AppSettingName.NamePrefix)?.Value;
            var namesuffix = dbContext.Set<AppSetting>().FirstOrDefault(x => x.Name == Enums.AppSettingName.NameSuffix)?.Value;
            var advLogo = dbContext.Set<AppSetting>().FirstOrDefault(x => x.Name == Enums.AppSettingName.Adv)?.Value;
            var advUrl = dbContext.Set<AppSetting>().FirstOrDefault(x => x.Name == Enums.AppSettingName.Url)?.Value;
            if (template == null)
            {
                Toast("未设置生成模板");
                return;
            }
            Toast("已开始生成页面，在生成完成之前，请不要随意刷新该页面");
            await Task.Delay(1000);
            generating = true;
            foreach (var gen in gens)
            {
                gen.Status = Enums.GenStatus.Wait;
            }
            Refresh();
            var templateCode = template.Value;
            string firstResultCode = null;
            var authors = dbContext.Authors.ToDictionary(x => x.Id, x => x.Name);
            var sizes = dbContext.Sizes.ToDictionary(x => x.Id, x => x.Name);
            var templateEngine = Scriban.Template.Parse(templateCode);
            var advs = dbContext.Advs.ToList();
            foreach (var gen in gens)
            {
                gen.Status = Enums.GenStatus.Processing;
                Refresh();
                var resultCode = templateEngine.Render(new
                {
                    ProductLogo = gen.Product.Image,
                    ProductName = gen.Product.Name,
                    ProductSize = sizes.GetValueOrDefault(gen.Product.SizeId, "未知"),
                    ProductNum = gen.Product.IdNumber,
                    ProductTime = gen.Product.CreationTime.ToString("yyyy.MM.dd"),
                    ProductAuthor = authors.GetValueOrDefault(gen.Product.AuthorId, "未知"),
                    ProductDescriptionTitle = gen.Product.DescriptionTitle,
                    ProductDescription = gen.Product.Description,
                    NamePrefix = nameprefix,
                    NameSuffix = namesuffix,
                    ProductAdvs = advs
                });
                firstResultCode = firstResultCode ?? resultCode;
                File.WriteAllText(Path.Combine(config.TargetPath, gen.Product.Id + ".html"), resultCode);
                gen.Status = Enums.GenStatus.Complete;
                await Task.Delay(10);
            }
            var filePath = Path.Combine(config.TargetPath, "index.html");
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.CreateText(filePath).Dispose();
            File.WriteAllText(filePath, firstResultCode);
            Toast("生成结束，现在可以刷新该页面");
            generating = false;
            MarkAsRequireRender();
        }

        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            gens = await dbContext.Set<Product>().Where(x => !x.IsDeleted).Select(x => new GenModel
            {
                Id = x.Id,
                Name = x.Name,
                Product = x,
                Status = x.Generated
            }).ToListAsync();
            await InvokeAsync(StateHasChanged);
        }
    }
}
